package org.hfy.collections.helper;

import org.hfy.Constants;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Author: Takagi
 * @date: 2023/4/26
 */
public class LRPredictTable {
    // 状态标签 : 状态
    Map<Symbol, State> predictTable = new HashMap<>();
    List<Symbol> stateNameList = new LinkedList<>();

    public State getState(Symbol name) {
        return this.predictTable.get(name);
    }

    public State getFirstState() {
        return this.predictTable.get(this.stateNameList.get(0));
    }

    public Symbol firstStateName() {
        return this.getFirstState().name;
    }

    /*
     * @Author Takagi
     * @Description: 预测分析表添加状态名
     * @date: 2023/4/27
     * @param stateName
     * @return
     **/
    public void addStateName(Symbol stateName) {
        this.stateNameList.add(stateName);
    }

    /*
     * @Author Takagi
     * @Description: 设置预测分析表的状态
     * @date: 2023/4/27
     * @param stateName
     * @param state
     * @return
     **/
    public void setState(Symbol stateName, State state) {
        this.predictTable.put(stateName, state);
    }

    /*
     * @Author Takagi
     * @Description: 打印表头
     * @date: 2023/4/27
     * @param symbols
     * @return
     **/
    public void showTableHeader(Set<Symbol> symbols) {
        List<String> header = this.getTableHeader(symbols);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < header.size(); ++i) {
            sb.append(Constants.formatLine(header.get(i)));
            if (i < header.size() - 1) {
                sb.append("\t");
            }
        }
        System.out.println(sb);
    }

    /*
     * @Author Takagi
     * @Description: 获取表头的字段名列表
     * @date: 2023/4/27
     * @param symbols
     * @return * @return List<String>
     **/
    public List<String> getTableHeader(Set<Symbol> symbols) {
        Set<Symbol> terminators = symbols.stream().filter(Constants::isTerminator).collect(Collectors.toSet());
        Set<Symbol> nonTerminators = symbols.stream().filter(Constants::isNonTerminator).collect(Collectors.toSet());
        List<String> header = new LinkedList<>();
        header.add("state");
        header.addAll(terminators.stream().map(Object::toString).collect(Collectors.toList()));
        header.addAll(nonTerminators.stream().map(Object::toString).collect(Collectors.toList()));
        return header;
    }
}
